package com.qf.arith;

import java.util.HashSet;
import java.util.Set;

/**
 * 链表的中间元素
 *
 * @author lixu
 */
public class TestIsMiddle {


    //链表  单向
    static class Node<T> {
        T value;//值
        Node<T> next;//后继

        public Node(T value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        Node<Integer> node1 = new Node<>(3);
        Node<Integer> node2 = new Node<>(8);
        Node<Integer> node3 = new Node<>(1);
        Node<Integer> node4 = new Node<>(9);
        //Node<Integer> node5 = new Node<>(7);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
       // node4.next = node5;


        System.out.println("中间元素是:" + isMiddel(node1));


    }

    /**
     * 中间元素
     * @param node1
     * @return
     */
    private static Integer isMiddel(Node<Integer> node1) {
        //快指针
        Node<Integer> fast = node1;
        //慢
        Node<Integer> slow = node1;

        while (fast!=null && fast.next!=null){
            fast=fast.next.next;
            slow = slow.next;
        }
        return slow.value;


    }


}
